from flask import Blueprint, jsonify

from flask import Blueprint, request, render_template, redirect

from .models import *
from flask_cors import cross_origin

"""
此文件用于存放路由和视图函数
"""
# 创建蓝图
blue = Blueprint('user', __name__)
api = Blueprint('api', __name__)


# 学生成绩评级方法
def grade_check(item):
    if 0 <= item < 60:
        return '不及格'
    elif 60 <= item < 70:
        return '及格'
    elif 70 <= item < 80:
        return '良好'
    elif 80 <= item < 90:
        return '优良'
    elif 90 <= item <= 100:
        return '优秀'
    else:
        return 'null'


# 学生数据api
@api.route('/api/student/')
def student_view():
    page = request.args.get('page', type=int, default=1)  # 获取页数默认值1
    per_page = request.args.get('per_page', type=int, default=10)  # 获取每页多少条数据，默认值10
    paginate = Students.query.paginate(page=page, per_page=per_page, error_out=False)  # 分页查询数据库的学生
    items: [Students] = paginate.items  # 将分页查询的结果赋值给'items'变量，该变量是一个包含'Students'对象的列表。

    return {
        'code': 0,
        'msg': '信息查询成功',
        'count': paginate.total,
        'data': [
            {'id': item.id,
             's_id': item.s_id,
             'name': item.name,
             'age': item.age,
             'java': item._java,
             'java_grade': grade_check(item._java),
             'python': item._python,
             'python_grade': grade_check(item._python),
             'mysql': item._mysql,
             'mysql_grade': grade_check(item._mysql),
             'score': item.score
             } for item in items
        ]
    }


# 主页视图函数
@blue.route('/')
@blue.route('/index/')
def index():
    return render_template('index.html')


# 添加学生视图函数
@blue.route('/add_student/')
def student_add():
    return render_template('add_student.html')


# 添加学生
@api.post('/api/addStudent/')
def add_student():
    data = request.get_json()
    print(data)
    # 尝试将获取的信息插入数据库
    try:
        student = Students()
        student.s_id = data['s_id']
        student.name = data['name']
        student.age = data['age']
        student._java = data['_java']
        student._python = data['_python']
        student._mysql = data['_mysql']
        student.score = int(data['_java']) + int(data['_python']) + int(data['_mysql'])
        db.session.add(student)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        print(e)
        return {
            'code': -1,
            'msg': "新增数据失败"
        }

    return {
        'code': 0,
        'msg': "新增数据成功"
    }

# 批量添加学生
@api.route('/api/addStu/', methods=['POST'])
def add_stu():
    data = request.json
    print("data=>>", data)
    try:
        student = Students()
        student.s_id = data['s_id']
        student.name = data['name']
        student.age = data['age']
        student._java = data['_java']
        student._python = data['_python']
        student._mysql = data['_mysql']
        student.score = int(data['_java']) + int(data['_python']) + int(data['_mysql'])
        db.session.add(student)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        print(e)
        return "新增数据失败"

    return "新增数据成功"


# 编辑学生
@api.post('/api/editStudent/')
def edit_student():
    data = request.get_json()

    # 从数据库查询学生学号
    student = Students.query.filter_by(s_id=int(data['s_id'])).first()

    # 尝试将修改过的数据插入到数据库
    try:
        student.name = data['name']
        student.age = data['age']
        student._java = data['java']
        student._python = data['python']
        student._mysql = data['mysql']
        student.score = int(data['java']) + int(data['python']) + int(data['mysql'])
        # db.session.add(student)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        print(e)
        return {
            'code': -1,
            'msg': "修改数据失败"
        }

    return {
        'code': 0,
        'msg': "修改数据成功"
    }


# 删除学生
@api.post('/api/delStudent/')
def del_student():
    data = request.get_json()
    # 从数据库查询学生学号
    student = Students.query.filter_by(s_id=int(data['s_id'])).first()
    # 尝试删除学生
    try:
        db.session.delete(student)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        print(e)
        return {
            'code': -1,
            'msg': "删除数据失败"
        }

    return {
        'code': 0,
        'msg': "删除数据成功"
    }


@blue.route('/show_all/')
def show_all():
    return render_template('show_all.html')


# 数据展示

@api.route('/api/show/')
@cross_origin(supports_credentials=True)
def show():
    students = Students.query.all()
    sumjava = 0  # 求Java成绩总和
    sumpython = 0  # 求python成绩总和
    summysql = 0  # 求mysql成绩总和
    for student in students:
        sumjava += student._java
        sumpython += student._python
        summysql += student._mysql

    return {
        'code': 0,
        'msg': '信息查询成功',
        'sum': {
            'sumjava': sumjava,
            'sumpython': sumpython,
            'summysql': summysql
        },
        'data': [
            {'id': student.id,
             's_id': student.s_id,
             'name': student.name,
             'age': student.age,
             'java': student._java,
             'java_grade': grade_check(student._java),
             'python': student._python,
             'python_grade': grade_check(student._python),
             'mysql': student._mysql,
             'mysql_grade': grade_check(student._mysql),
             'score': student.score
             } for student in students
        ]
    }
